package net.lzzy.practices.web.models;

import lombok.Getter;
import lombok.Setter;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.utils.AuthUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @author 渊何
 */
@Getter
@Setter
public class VmUser {
     private UUID id;
     private String nickName;
     private String userName;
     private String email;
     private String phone;
     private String avatar;
     private String token;
     private int type;
     private Date lastLogin;

     private VmUser(){}

     private VmUser(User user){
          id = user.getId();
          userName = getUserName();
          nickName = user.getNickName();
          email = user.getEmail();
          phone = user.getPhone();
          avatar = user.getAvatar();
          type = user.getType();
          lastLogin = new Date();
          token = UUID.randomUUID().toString();
          AuthUtils.USERS.add(this);
     }

     public static VmUser apiLogin(User user){
          VmUser vmUser = AuthUtils.USERS
                  .stream()
                  .filter(u -> u.userName.equals(user.getUserName()))
                  .findFirst()
                  .orElse(null);
          if (vmUser == null){
               vmUser = new VmUser(user);
          }else {
               vmUser.lastLogin = new Date();
          }
          return vmUser;
     }

     public static VmUser create (User user, boolean admin){
          VmUser vm = new VmUser();
          vm.setId(user.getId());
          vm.setNickName(user.getNickName());
          vm.setAvatar(user.getAvatar());
          vm.setEmail(user.getEmail());
          vm.setToken("");
          vm.setType(User.TYPE_STUDENT);
          if(admin){
               vm.setPhone(user.getPhone());
               vm.setUserName(user.getUserName());
               vm.setType(user.getType());
          }
          return vm;
     }
}
